<template>
  <div class="newGroupSend flex-row">
    
    <div class="sendContentAndType flex-column">
        <el-card class="send-setting-account">
          <choose-service-account title="" @serviceChange="serviceChange" :defalutcheckedWxid="reEditParams.checkedWxid">
          </choose-service-account>
        </el-card>
        <el-card class="send-setting-content">
          <div slot="header" class="clearfix">
            <span>发送内容（最多添加10条内容）</span>
          </div>
          <messageButtonGroup
              :csid="csid"
              :wxid="currentServices[0]&&currentServices[0].wxid"
              @create="setSendContent"
              :types="['text','image','video','link','file','notice',currentServices.length>1?'':'card','document','forward']"
            />
          <el-divider></el-divider>
          <div>注意：群公告只能向是群主的群发送，且只每次只能发送一条消息</div>
          <el-divider v-if="sendContent.length"></el-divider>
          <div class="quick-plane">
            <div class="quick-item" v-for="(reply, index) in sendContent" :key="index">
              <div class="quick-item-createtime" style="text-align:right">
                  <i @click.stop="sendContent.splice(index,1)" class="el-icon-close quick-item-close"></i>
              </div>
              <messageCard :message="reply" />
            </div>
          </div> 
        </el-card>
      </div>
    <el-card class="sendFilter flex-column" style="flex-shrink: 0;">
      <div slot="header" class="clearfix">
        <span>群发对象</span>
      </div> 
      <div class="radioContainer">
        <el-radio-group v-model="sendType" @change="changeSendType">
          <el-radio-button label="user">好友</el-radio-button>
          <el-radio-button label="group">群聊</el-radio-button>
        </el-radio-group>
      </div>
      <div class="searchWrap">
        <input type="text" name="title" :placeholder="sendType=='group' ? '请输入群名称关键词' : '请输入好友昵称'" autocomplete="off" class="layui-input groupSearch" v-model="searchKeyWord">
      </div>
      <div class="groupMemberFilter flex-row" v-if="sendType=='group'">
        <label class="layui-form-label">群人数</label>
        <div class="layui-input-inline" style="width: 100px;">
          <input type="text" name="price_min" autocomplete="off" class="layui-input" v-model="minCount">
        </div>
        <div class="layui-form-mid">-</div>
        <div class="layui-input-inline" style="width: 100px;">
          <input type="text" name="price_max" autocomplete="off" class="layui-input" v-model="maxCount">
        </div>
      </div>
      <div class="groupManagerFilter flex-row" v-if="sendType=='group'">
        <label>群主</label>
        <div class="radioWrap">
          <label>
            <input type="radio" name="manager" value="0" :checked="groupFilterType===0" @change="changeManagerType">群主
          </label>
          <label>
            <input type="radio" name="manager" value="1" :checked="groupFilterType===1" @change="changeManagerType">非群主
          </label>
        </div>
      </div>
      <div class="groupChatsTitle flex-row" v-if="sendType=='group'">
        <input type="checkbox" class="selectAll" v-model="selectAllGroup">
        <p>群聊 ({{checkedGroups.length}}/{{groups.length}})</p>
      </div>
      <div class="groupChatsTitle flex-row" v-if="sendType=='user'" style="margin-top: 8px;">
        <input type="checkbox" class="selectAll" v-model="selectAllFriend">
        <p>好友 ({{checkedMembers.length}}/{{members.length}})</p>
      </div>
      <div class="groupChats autoGrow flex-column">
        <slot v-if="sendType=='group'">
          <label v-for="(group, index) in filterGroups" :key="index" class="send-item">
            <input type="checkbox"
                @change="changeGroup(group, $event)"
                :checked="checkedGroups.filter(g=>g.wxid == group.wxid).length">
            <group 
              :avatar="group.avatar" 
              :name="group.groupname"  
              :member="group.personnum"
              :friend="group.friendNum"
              class="send-item-friend"
            />
            <span class="fontGrey textEllipsis send-item-account">{{accountsWxidMap[group.wxaccount]['name']}}</span>
          </label>
        </slot>
        <slot v-if="sendType=='user'">
          <label v-for="(member, index) in filterMembers" :key="index" class="send-item">
            <input type="checkbox"
                @change="changeMember(member, $event)"
                :checked="checkedMembers.filter(m=>m.wxid == member.wxid).length">
            <friend 
              :avatar="member.avatar" 
              :name="member.friendnick"  
              :gender="member.friendsex"
              :wxid="member.friendwxid"
              class="send-item-friend"
            />
            <span class="fontGrey textEllipsis send-item-account">{{accountsWxidMap[member.wxaccount]['name']}}</span>
           
          </label>
        </slot>
      </div>
    </el-card>
      
    <div class="sendTo flex-column">
      <el-card class="send-card">
         <div slot="header" class="clearfix">
            <span v-if="sendType=='group'">发送对象({{checkedGroups.length}}个群)</span>
            <span v-else>发送对象({{checkedMembers.length}}个好友)</span>
        </div> 

        <div class="flex-row autoGrow list">
            <label class="list-item" v-for="member in (sendType=='group'?checkedGroups:checkedMembers)" :key="member.wxid">
              <input type="checkbox" v-if="sendType=='user'" @change="changeMember(member, $event)" :checked="true">
              <input type="checkbox" v-else @change="changeGroup(member, $event)" :checked="true">
              <friend 
                :avatar="member.avatar"
                :name="member.friendnick"
                :wxid="member.friendalias||member.friendwxid"
                :gender="member.gender"
                class="list-item-friend"
                v-if="sendType=='user'"
              /> 
              <group
                :avatar="member.avatar"
                :name="member.groupname"
                :member="member.personnum"
                :friend="member.friendNum"
                class="list-item-friend"
                v-if="sendType=='group'"
              />

                <div class="attachInfo flex-row belongToService">
                    <span class="serviceBelong fontGrey">归属客服</span>
                    <friend 
                      :avatar="getAccountByWxid(member.wxaccount).avatar"
                      :name="getAccountByWxid(member.wxaccount).nick"
                      :wxid="getAccountByWxid(member.wxaccount).wxid||getAccountByWxid(member.wxaccount).alias"
                      class="list-item-friend"
                    /> 
                  </div>
            </label>
        </div>
      </el-card>
      
      <div class="sendBtns">
        <button class="layui-btn" @click="sendNow">即时发送</button>
        <button class="layui-btn layui-btn-primary" @click="setSendTime" id="dateDialog">定时发送</button>
      </div>
    </div>
    <!-- 文本弹窗  -->
    <el-dialog :close-on-click-modal="false" :visible.sync="showDatePicker" width="400px" append-to-body>
        <div slot="title" style="display: flex; flex-direction: row;justify-content: space-between;">
            <span>定时发布</span>
        </div>
        <div class="edit-form">
          <div class="date-dialog-item" v-for="(item, index) in sendDates" :key="index" >
            <el-date-picker
              size="small"
              type="datetime"
              v-model="sendDates[index]"
              :default-time="defaultTime"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
              >
            </el-date-picker>
            <el-button type="primary" size="small" @click="addSendDate" v-if=" index === 0&&sendDates.length===1 || index === sendDates.length-1 ">增加</el-button>
            <el-button type="danger" size="small" @click="delSendDate(index)" v-else>删除</el-button>  

          </div> 
          <div class="date-dialog-item">
            <el-button type="primary" @click="submitSendTime">发送</el-button>  
          </div>      
        </div>
    </el-dialog>
     
  </div>
</template>
<script>
import { mapState } from 'vuex';
import UserListItem from '@/components/userListItem';

import ServiceListItem from '@/components/serviceListItem';
import QuickReplies from './quickReplies';
import ChooseServiceAccount from '@/components/chooseServiceAccount';
import messageButtonGroup from '@/components/message-button-group'
import messageCard from '@/components/message-card'

import { formatTime } from '@/lib/utils'
import pinyin from '@/lib/pinyin'
import friend from '@/components/friend'
import group from '@/components/group'

export default {
  data() {
    return {
      currentServices: [],
      searchKeyWord: '',
      minCount: 0,
      maxCount: 500,
      managerType: 'owner',
      sendType: 'user', // group
      sendContent: [],
      selectAllGroup: false,
      selectAllFriend: false,
       
      checkedGroups: [],
       
      checkedMembers: [],
      showDatePicker: false,
      groups: [],
      members: [],
      reEditParams:{},
      groupFilterType:0,

      today : 0,
      defaultTime:'',
      pickerOptions: {
          disabledDate:(time)=>{
            return +time < this.today
          }
      },
      sendDates:['']
    }
  },
  created(){
    
     var params = this.$route.params||{};
     const { msgextra,receivers,content } = params;
     let checkedWxid;
     if(msgextra){
       let selectAccount = []
       checkedWxid = msgextra.split(',').map(id=>{
          const account = this.accountsWxidMap[id]
          selectAccount.push(account)
          return account.wxid
       })
       this.serviceChange(selectAccount)
     }
     if( receivers && receivers[0] ){
       if( receivers[0].toaccount.endsWith('@chatroom') ){
        this.checkedGroups = receivers.map(item=>{
          return {...item,wxaccount:item.fromaccount,friendwxid:item.toaccount,wxid:item.id}
        })
        this.changeSendType('group')
       }else{
         this.checkedMembers = receivers.map(item=>{
          return {...item,wxaccount:item.fromaccount,friendwxid:item.toaccount,wxid:item.toaccount}
        })
        this.changeSendType('user')
       }
       
     }
     if(content){
       this.setSendContent( content )
     }

     this.reEditParams = {...params,checkedWxid} 
  },
  components: {
    UserListItem,
    ServiceListItem,
    QuickReplies,
    ChooseServiceAccount,
    messageButtonGroup,
    messageCard,
    friend,group
  },
  props: ['intervalCount', 'intervalTime'],
  methods: {
    formatTime,
    changeSendType(value) {
      console.log(value)
      this.sendType = value
      this.searchKeyWord = ''
      this.groupFilterType = 0

    },
    changeManagerType(e) {
      this.groupFilterType = +e.target.value
    },
    changeGroup(group, e) {
      if (e.target.checked) {
        this.checkedGroups.push(group)
      } else {
        this.checkedGroups = this.checkedGroups.filter(g=>{
          console.log(g.wxid,group.wxid)
          return g.wxid != group.wxid
        })
      }
    },
    changeMember(member, e) {
      if (e.target.checked) {
        this.checkedMembers.push(member)
      } else {
        this.checkedMembers = this.checkedMembers.filter(g=>g.wxid != member.wxid)
      }
    },
    sendNow() {
      this.send()
    },
    setSendTime() {
      this.showDatePicker = true
    },
    addSendDate(){
      this.sendDates.push('')  
    },
    delSendDate(index){
      this.sendDates.splice(index,1)
    },
    dateChange(e){
      console.log(e)
    },
    submitSendTime() {
      const times = this.sendDates.filter(item=>item)
      this.send(JSON.stringify(times))
      this.showDatePicker = false;
    },
    serviceChange(services) {
      this.currentServices = services
      this.getServicesFriends(services).then(data=>{
        this.members = data.filter(m=>{
          return !(m.isbrand || m.isent)
        })
      })
      this.getServicesGroups(services).then(data=>{
        this.groups = data
      })

      if(services.length>1){
        this.sendContent = this.sendContent.filter(item=>item.msgtype!=13)
      }

    },
    setSendContent(content) {
      //console.log(contents)
      if(content instanceof Array){
        this.sendContent= content 
      }else{
        if(this.sendContent.length>=10){
          this.$message({
            showClose: true,
            message: '群发消息上线10条，无法继续添加！',
            type: 'error'
          });
        }else{
          this.sendContent.unshift(content)
        }
        
      }
      
    },
    send(time) {
      const sendContent = [...this.sendContent]
      if (!Object.keys(sendContent).length) return this.$msg("请填写要群发的内容")
      const type = this.sendType == 'group' ? 1 : 0
      const reveivers = type == 1 ? this.checkedGroups : this.checkedMembers
      if (!reveivers.length) return this.$msg("请选择要群发对象")

     let csid = this.uistate.adminid;
     let groupIds = []
     reveivers.forEach(reveiver=>{
         let _group = {
             fromAccount : reveiver.wxaccount,
             toAccount :  reveiver.groupno||reveiver.wxid
          }
          groupIds.push(_group)
       })
      const msgExtra = Array.from(new Set( groupIds.map(item=>item.fromAccount) )).join(',')
      const params =  {
        csId:csid,
        groupIds,sendTime:time,
        msg: JSON.stringify(sendContent.reverse()),
        batchInterval: this.intervalTime || 5,
        batchSize: this.intervalCount || 50,
        msgExtra,
        msgtype:type
      }
      this.$api.groupSend.send(params).then(rs=>{
        this.$msg('任务创建成功')
        this.$router.push({
          name:'GroupSendHistory'
        })
      }).catch(e=>this.$msg(e))

    },
    getAccountByWxid(wxid){
      return Object.values(this.accountMap).filter(s=>s.wxid == wxid)[0]  
    }
  },
  watch: {
    sendDates(val){
      console.log(val)
    },
    showDatePicker(val){
      const cur = new Date()
      this.today = +new Date(formatTime(cur,'yyyy/MM/dd'))
      this.defaultTime = cur.getHours()+':'+( cur.getMinutes()+1)+':'+cur.getSeconds()
      this.sendDates = ['']
    },
    selectAllGroup(val) {
      if (val) {
        this.checkedGroups = this.filterGroups
        return
      }
      this.checkedGroups = []
    },
    selectAllFriend(val) {
      if (val) {
        this.checkedMembers = this.filterMembers
        return
      }
      this.checkedMembers = []
    } 
  },
  computed: {
    ...mapState(['manager', 'services','uistate','accountMap','accountListMap']),
    accountsWxidMap(){
        const {adminid} = this.uistate
        if( adminid ===-1 || !this.accountListMap[adminid] )return []
        let map = {}
        this.accountListMap[adminid].forEach(id=>{
            const item = this.accountMap[id]
            map[item.wxid] = {
                id:item.id,
                csid:item.csid,
                name:item.nick,
                avatar:item.avatar,
                wxid:item.wxid,
                gender:item.gender,
                friendcount:item.friendcount
            }
        })
        return map

    },
    csid(){
      return this.uistate.adminid
    },
    totalMessages() {
      let messages = []
      for (let key in this.messages) {
        messages = [...messages, ...this.messages[key]]
      }
      return messages
    },
    filterGroups(){
      const searchKeyWord = this.searchKeyWord
      const groupFilterType = this.groupFilterType
      const minCount = this.minCount
      const maxCount = this.maxCount
      const keyword = pinyin.getFullChars(searchKeyWord).toLocaleLowerCase()
      return this.groups.filter(g=>{
        const chars = pinyin.getFullChars(g.groupname+g.groupno).toLocaleLowerCase()
        const {personnum,friendNum,isfirst} = g
        
        if(chars.indexOf(keyword)>=0 && personnum>=minCount && personnum<=maxCount  ){
          if(groupFilterType === 0){
            return isfirst == 1
          }else{
            return isfirst != 1
          }
        }else{
          return false
        } 
        
      })
    },
    filterMembers(){
      const searchKeyWord = this.searchKeyWord
      const keyword = pinyin.getFullChars(searchKeyWord).toLocaleLowerCase()

      return this.members.filter(m=>{
        const chars = pinyin.getFullChars(m.friendnick+m.friendwxid+m.friendalias).toLocaleLowerCase()
        if(m.isbrand || m.isent)return false
        return chars.indexOf(keyword)>=0 
      })
    },
    accounts(){
      const csid = this.csid
      console.log('accounts',this.accountListMap)
      const list = this.accountListMap[csid]
      if(!list )return []
      return list.map(id=>this.accountMap[id])
    }
  },
}
</script>
<style scoped>
.setSendInfo{
  height: auto;
  overflow: initial;
  background: #fff;
  width:auto;
}
.setSendInfo .infoTitle{
  margin: 0;
}
.sendContentAndType{
  padding: 0 10px;
  width: 260px;
  height: 100%;
}
.send-setting-account{
  overflow: inherit;
}
.send-setting-content{
  margin-top: 10px;
    overflow: auto; 
}
.send-item{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
}
.send-item-friend{
  width: 130px;
  padding: 0 5px;
  flex-shrink: 0
}
.send-item-account{
  flex:1;
  text-align: right;
}
.quick-plane{
    height: 100%;
    overflow: auto;
    /* padding: 0 10px;
    background: #f1f1f1; */
}
.quick-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}
.newGroupSend{ height: 100%; }
.groupSendContainer .searchWrap, .groupSendContainer .groupMemberFilter, .groupSendContainer .groupManagerFilter, .groupSendContainer .groupChatsTitle, .groupSendContainer .groupChats{
  padding: 0
}
.radioContainer{
  display: flex;
  justify-content: center;
}
.searchWrap{
  margin-top: 10px;
}
.groupSendContainer .attachInfo{
  width: 400px;
}
.list{
  display: flex;
  flex-direction: column;
}
.list-item{
  padding: 10px 16px;
  background-color: #fff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
  margin: 5px 0;  
  cursor: pointer; 
  box-shadow: 0px 1px 1px 1px #ddd;
  transition:transform 200ms;
  padding-right: 10px; 
  display: flex;
  flex-direction: row;
  align-items: center;
}
.list-item:hover{
  transform:translateX(-10px) 
}
.list-item-friend{
  flex:1;
  margin-left: 10px;
}
.send-card{
  height: 100%;
  margin: 10px;
}
.send-card >>> .el-card__body{
  overflow: auto;
  height: 100%;
}

.date-dialog-item{
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
}
.date-dialog-item .el-input{
  flex:1;
  margin-right: 10px;
}
.date-dialog-item .el-button{
  
}
</style>
